// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// n [author] rhyme_lph
// P [email]  rhymelph@gmail.com
// u [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/dashboard_reimburse_entity.dart';
import 'package:finance_app/src/entities/payslips_entity.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_overview_provider.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_view_provider.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/chart/normal_bar_two_way_chart.dart';
import 'package:finance_app/src/widgets/chart/normal_circle_chart.dart';
import 'package:finance_app/src/widgets/chart/normal_line_chart.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:flutter_svg/flutter_svg.dart';

class DashboardOverviewView extends StatefulWidget {
  @override
  _DashboardOverviewViewState createState() => _DashboardOverviewViewState();
}

class _DashboardOverviewViewState extends State<DashboardOverviewView>
    with
        StatefulPresenter<DashboardOverviewView, DashboardViewProvider,
            DashboardOverviewProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) =>
      Config.hasPermission(PermissionUtils.salesReport) ||
              Config.hasPermission(PermissionUtils.expense) ||
              Config.hasPermission(PermissionUtils.accountantReports)
          ? ListView(
              key: PageStorageKey("Tab0"),
              physics: const ClampingScrollPhysics(),
              children: [
                if (Config.hasPermission(PermissionUtils.salesReport))
                  _buildSalesTrendTable(),
                if (Config.hasPermission(PermissionUtils.expense))
                  _buildExpensesTable(),
                if (Config.hasPermission(PermissionUtils.accountantReports))
                  _buildProfitLossTable(),
              ],
            )
          : buildNoPermissionWidget(context);

  _buildChartTab({Color color, String title}) => Row(
        children: [
          Container(
            width: getDp(11),
            height: getDp(11),
            margin: EdgeInsets.only(right: getDp(10)),
            decoration: BoxDecoration(
                color: color, borderRadius: BorderRadius.circular(getDp(2))),
          ),
          Text(
            title,
            style: TextStyle(
              color: aceBlackColor,
              fontSize: getSp(14),
              fontWeight: FontWeight.w400,
              height: 1,
            ),
          ),
        ],
      );

  Widget _buildExpensesTable() => _buildClickItem(
      onTap: provider.onNavExpenses,
      child: listBuilder<DashboardReimburseEntity>(
        selector: (_, __) => __.expense,
        builder: (BuildContext context, DashboardReimburseEntity value,
                Widget child) =>
            value == null
                ? Container()
                : NormalCircleChart(
                    emptyTip: S.current.no_category_found,
                    itemTitle: value?.title ?? S.current.top_expenses,
                    itemList: value?.chartData?.map((e) => e.name)?.toList(),
                    valueList: value?.chartData
                        ?.map((e) => e.value.toDouble())
                        ?.toList(),
                    currency: value?.currencyCode ?? "SGD",
                    total: value?.total ?? '0.00',
                  ),
      ),
      top: Row(
        children: [
          listBuilder<DashboardReimburseEntity>(
            selector: (_, __) => __.expense,
            builder: (BuildContext context, DashboardReimburseEntity value,
                    Widget child) =>
                value == null
                    ? Container()
                    : Text(
                        '${S.current.expenses} (${value.currencyCode})',
                        style: TextStyle(
                          color: aceBlackColor,
                          fontSize: getSp(16),
                          fontWeight: FontWeight.w400,
                          height: 16 / 14,
                        ),
                      ),
          ),
          Spacer(),
          SvgPicture.asset(
            A.assetsImagesRight,
            width: getDp(18),
            height: getDp(13),
          ),
        ],
      ));

  Widget _buildProfitLossTable() => _buildClickItem(
      onTap: provider.onNavProfitLoss,
      child: listBuilder<PayslipsEntity>(
        selector: (_, __) => __.profileLoss,
        builder: (BuildContext context, PayslipsEntity value, Widget child) =>
            value == null
                ? Container(
                    padding: EdgeInsets.symmetric(vertical: 100),
                    child: CircularProgressIndicator(),
                  )
                : NormalBarTwoWayChart(
                    data: value,
                  ),
      ),
      top: Row(
        children: [
          listBuilder<DashboardReimburseEntity>(
            selector: (_, __) => __.expense,
            builder: (BuildContext context, DashboardReimburseEntity value,
                    Widget child) =>
                value == null
                    ? Container()
                    : Text(
                        '${S.current.profit__loss} (${value.currencyCode})',
                        style: TextStyle(
                          color: aceBlackColor,
                          fontSize: getSp(16),
                          fontWeight: FontWeight.w400,
                          height: 16 / 14,
                        ),
                      ),
          ),
          Spacer(),
          SvgPicture.asset(
            A.assetsImagesRight,
            width: getDp(18),
            height: getDp(13),
          ),
        ],
      ),
      bottom: Column(
        children: [
          AppSpaces.h15,
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildChartTab(color: aceGreenColor, title: S.current.net_profit),
              AppSpaces.w28,
              _buildChartTab(color: aceRedColor, title: S.current.net_loss),
            ],
          ),
          AppSpaces.h30,
        ],
      ));

  Widget _buildSalesTrendTable() => _buildClickItem(
      onTap: provider.onNavSalesTrend,
      child: listBuilder<PayslipsEntity>(
        selector: (_, __) => __.salesTrend,
        builder: (BuildContext context, PayslipsEntity value, Widget child) =>
            value == null
                ? Container(
                    padding: EdgeInsets.symmetric(vertical: 100),
                    child: CircularProgressIndicator(),
                  )
                : NormalLineChart(
                    data: value,
                  ),
      ),
      top: Row(
        children: [
          listBuilder<DashboardReimburseEntity>(
            selector: (_, __) => __.expense,
            builder: (BuildContext context, DashboardReimburseEntity value,
                    Widget child) =>
                value == null
                    ? Container()
                    : Text(
                        '${S.current.sales_trend} (${value.currencyCode})',
                        style: TextStyle(
                          color: aceBlackColor,
                          fontSize: getSp(16),
                          fontWeight: FontWeight.w400,
                          height: 16 / 14,
                        ),
                      ),
          ),
          buildSalesTrendType(),
          Spacer(),
          SvgPicture.asset(
            A.assetsImagesRight,
            width: getDp(18),
            height: getDp(13),
          ),
        ],
      ));

  PressedOpacityButton buildSalesTrendType() {
    return PressedOpacityButton(
      padding: EdgeInsets.symmetric(horizontal: getDp(20)),
      onPressed: provider.onSelectSaleTrend,
      child: Row(
        children: [
          listBuilder<String>(
              builder: (BuildContext context, String value, Widget child) =>
                  value == null
                      ? Container()
                      : Text(
                          value,
                          style: TextStyle(
                            color: aceBlueColor,
                            fontSize: getSp(16),
                            fontWeight: FontWeight.w700,
                            height: 14 / 16,
                          ),
                        ),
              selector: (_, __) => __.currentSelectSalesTrend),
          SizedBox(
            width: getDp(5),
          ),
          SvgPicture.asset(
            A.assetsImagesStyleArrowBlack,
            color: aceBlueColor,
            width: getDp(7),
            height: getDp(7),
            fit: BoxFit.contain,
          ),
        ],
      ),
    );
  }

  Widget _buildClickItem(
          {Widget child, Widget top, VoidCallback onTap, Widget bottom}) =>
      Container(
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                bottom: BorderSide(
              color: aceGrayColor,
              width: getDp(0.5),
            ))),
        padding: EdgeInsets.symmetric(
          horizontal: getDp(21),
          vertical: getDp(14),
        ),
        child: Column(
          children: [
            PressedOpacityButton(onPressed: onTap, child: top),
            AppSpaces.h20,
            child,
            if (bottom != null) bottom,
          ],
        ),
      );
}
